package com.github.sbb.sherry.console.service.engine.config;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.sbb.sherry.common.base.ValidateResult;
import com.github.sbb.sherry.console.dto.PageList;
import com.github.sbb.sherry.primitives.config.calcparam.ExpressionSymbol;
import com.github.sbb.sherry.repository.entity.RuleParamConfig;
import com.github.sbb.sherry.repository.entity.RuleParamConfigExample;
import com.github.sbb.sherry.repository.mapper.RuleParamConfigMapper;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RuleParamConfigService {

  @SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
  @Autowired
  private RuleParamConfigMapper ruleParamConfigMapper;

  public PageList<RuleParamConfig> pageList(int currentPage, Integer pageSize) {
    if (pageSize == null) {
      pageSize = 10;
    }

    Page<RuleParamConfig> page = PageHelper.startPage(currentPage, pageSize);

    RuleParamConfigExample example = new RuleParamConfigExample();

    List<RuleParamConfig> rulesParams = ruleParamConfigMapper.selectByExample(example);

    if (page.getPages() < currentPage) {
      rulesParams = new ArrayList<>();
    }

    return PageList.of(currentPage, pageSize, page.getTotal(), rulesParams);
  }

  public void add(RuleParamConfig rulesParam) {
    validate(rulesParam);

    rulesParam.setId(null);
    if (rulesParam.getType() == 2) {
      rulesParam.setFetcher("");
      String expressionSymbols = rulesParam.getExpressionSymbols();
      List<ExpressionSymbol> expressionSymbolsList = JSON
          .parseObject(expressionSymbols, new TypeReference<List<ExpressionSymbol>>() {
          });
      String expression = expressionSymbolsList.stream().map(ExpressionSymbol::getSymbol)
          .collect(Collectors.joining(" "));
      rulesParam.setExpression(expression);
    } else {
      rulesParam.setExpression("");
      rulesParam.setExpressionSymbols("");
    }
    ruleParamConfigMapper.insertSelective(rulesParam);
  }

  private void validate(RuleParamConfig ruleParamConfig) {
    com.github.sbb.sherry.primitives.config.calcparam.RuleParamConfig ruleCalcParamConfig = new com.github.sbb.sherry.primitives.config.calcparam.RuleParamConfig();

    BeanUtils.copyProperties(ruleParamConfig, ruleCalcParamConfig);

    ValidateResult validate = ruleCalcParamConfig.validate();
    if (validate.isFailure()) {
      throw new IllegalArgumentException(validate.getMessage());
    }
  }
}

